package com.guoguo.service.impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.TaskResource;
import com.guoguo.entity.PointFlow;
import com.guoguo.entity.TaskInfo;
import com.guoguo.entity.UserOther;
import com.guoguo.entity.UserTaskInfo;
import com.guoguo.entity.vo.TaskInfoDayVO;
import com.guoguo.entity.vo.TaskInfoVO;
import com.guoguo.mapper.InviteRelationMapper;
import com.guoguo.mapper.OrdersMapper;
import com.guoguo.mapper.PointFlowMapper;
import com.guoguo.mapper.TaskInfoMapper;
import com.guoguo.mapper.UserExtMapper;
import com.guoguo.mapper.UserOtherMapper;
import com.guoguo.mapper.UserTaskInfoMapper;
import com.guoguo.service.UserTaskInfoService;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.UUIDUtils;
import com.guoguo.utils.nowpay.DateHelper;

@Service
public class UserTaskInfoServiceImpl implements UserTaskInfoService {

	@Autowired
	private UserTaskInfoMapper userTaskInfoMapper;

	@Autowired
	private TaskInfoMapper taskInfoMapper;

	@Autowired
	private UserExtMapper userExtMapper;

	@Autowired
	private UserOtherMapper userOtherMapper;

	@Autowired
	private OrdersMapper ordersMapper;

	@Autowired
	private PointFlowMapper pointFlowMapper;
	
	@Autowired
	private InviteRelationMapper inviteRelationMapper;

	@Override
	public List<UserTaskInfo> getUserTaskInfo(String userId, String startTime, String endTime, Integer start, Integer size) {
		return userTaskInfoMapper.selectList(userId, startTime, endTime, start, size);
	}

	@Override
	public void addUserTaskInfo(String userId, Integer giftType, Integer requireType) {
		RedisUtils redisUtils = RedisUtils.getInstance();
		if (giftType == 1) {
			if (!redisUtils.hexists(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString())) {
				redisUtils.hset(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString(), "1");
			} else {
				redisUtils.hincrby(TaskResource.REDIS_WEEK_TASK_STATUS + userId, TaskResource.GIFT_SIGN_TYPE.toString(), 1L);
			}
			redisUtils.expire(TaskResource.REDIS_WEEK_TASK_STATUS + userId, DateHelper.getWeekLastTime());
			// 调用奖励接口
			return;
		}
		if (!redisUtils.hexists(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString())) {
			redisUtils.hset(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString(), "1");
		} else {
			redisUtils.hincrby(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString().toString(), 1L);
		}
		redisUtils.expire(TaskResource.REDIS_DAY_TASK_STATUS + userId, DateHelper.getTodayLastTime());
		TaskInfo taskInfo = JSONObject.toJavaObject(JSONObject.parseObject(redisUtils.hget("TASK:DAY:INFO", requireType.toString())), TaskInfo.class);
		if (Integer.valueOf(redisUtils.hget(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString())) >= taskInfo.getRequireCount()) {
			// 调用奖励接口
			return;
		}
	}

	/**
	 * @Description： 查询redis缓存中每周礼包进度
	 * @author: WYZ
	 * @since: 2017年11月9日 下午6:25:09
	 */
	@Override
	public Integer selectWeekCount(String userId) {
		RedisUtils redisUtils = RedisUtils.getInstance();
		Integer weekTaskCount = null;
		if (!redisUtils.hexists(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString())) {
			redisUtils.hset(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString(), "1");
		} else {
			redisUtils.hincrby(TaskResource.REDIS_WEEK_TASK_STATUS + userId, TaskResource.GIFT_SIGN_TYPE.toString(), 1L);
		}
		redisUtils.expire(TaskResource.REDIS_WEEK_TASK_STATUS + userId, DateHelper.getWeekLastTime());
		weekTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString()));
		return weekTaskCount;
	}

	/**
	 * @Description： 查询redis缓存中每天礼包进度
	 * @author: WYZ
	 * @since: 2017年11月9日 下午6:25:09
	 */
	@Override
	public Integer selectDayCount(String userId, Integer requireType) {
		RedisUtils redisUtils = RedisUtils.getInstance();
		Integer dayTaskCount = null;
		if (!redisUtils.hexists(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString())) {
			redisUtils.hset(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString(), "1");
		} else {
			redisUtils.hincrby(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString().toString(), 1L);
		}
		redisUtils.expire(TaskResource.REDIS_DAY_TASK_STATUS + userId, DateHelper.getTodayLastTime());
		dayTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString()));
		return dayTaskCount;
	}

	/**
	 * @Description： 礼包中心首页
	 * @author: WYZ
	 * @since: 2017年11月9日 下午6:25:09
	 */
	@Override
	public Map<String, Object> giftCentre(String userId) {
		RedisUtils redisUtils = RedisUtils.getInstance();
		Integer weekTaskCount = null;
		Map<String, Object> data = new HashMap<String, Object>();
		List<TaskInfoVO> weekTaskList = new ArrayList<>();
		List<TaskInfoDayVO> dayTaskList = new ArrayList<>();
		Integer isWeekGet = null;
		Integer isDayGet = null;
		List<Integer> listType = new ArrayList<Integer>();
		// 查询每周的任务信息
		if (!redisUtils.hexists(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString())) {
			redisUtils.hset(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString(), "1");
		}
		weekTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString()));
		redisUtils.expire(TaskResource.REDIS_WEEK_TASK_STATUS + userId, DateHelper.getWeekLastTime());
		
		/*if (!redisUtils.hexists("TASK:WEEK:INFO:" + userId, "1")) {
		    redisUtils.hset("TASK:WEEK:INFO:", weekTaskCount.toString(), "1");
	    }
	    redisUtils.expire("TASK:WEEK:INFO:" + userId, DateHelper.getWeekLastTime());
	    TaskInfo taskInfo = JSONObject.toJavaObject(JSONObject.parseObject(redisUtils.hget("TASK:WEEK:INFO:", "1")), TaskInfo.class);*/
	    
		//查询礼包所有的类型
		listType = taskInfoMapper.selectAllGiftType();
		for (Integer giftType : listType) {
			if(giftType == TaskResource.GIFT_SIGN_TYPE){
				weekTaskList = taskInfoMapper.selectAllList(giftType);
				// 查询每周当天的礼包是否已经领取
				isWeekGet = userTaskInfoMapper.selectIsGetReward(userId,giftType, weekTaskCount-1, new Date());
				for (TaskInfoVO taskInfoVO : weekTaskList) {
					if (taskInfoVO.getPrizeCount2() == null) {
						taskInfoVO.setPrizeType2(0);
						taskInfoVO.setPrizeCount2(0);
					}
					if (taskInfoVO.getPrizeCount3() == null) {
						taskInfoVO.setPrizeType3(0);
						taskInfoVO.setPrizeCount3(0);
					}
					taskInfoVO.setGiftSort(TaskResource.Gift_WEEK_Sort);
					taskInfoVO.setCurrentCount(weekTaskCount);
					if (isWeekGet > 0) {// 查询当天的奖励是否已经领取
						taskInfoVO.setCurrentStatus(3);// 已领取
						taskInfoVO.setCurrentStatusName(TaskResource.CURRENT_ED_STATUS);
					} else {
						taskInfoVO.setCurrentStatus(1);// 可领取
						taskInfoVO.setCurrentStatusName(TaskResource.CURRENT_CAN_SIGN_STATUS);
					}
				}
			}else{
				// 查询每天的任务信息
				dayTaskList = taskInfoMapper.selectDayList(giftType);
				for (TaskInfoDayVO taskInfoDayVO : dayTaskList) {
					if (taskInfoDayVO.getPrizeCount2() == null) {
						taskInfoDayVO.setPrizeType2(0);
						taskInfoDayVO.setPrizeCount2(0);
					}
					if (taskInfoDayVO.getPrizeCount3() == null) {
						taskInfoDayVO.setPrizeType3(0);
						taskInfoDayVO.setPrizeCount3(0);
					}
					Integer dayTaskCount = null;
					if (!redisUtils.hexists(TaskResource.REDIS_DAY_TASK_STATUS + userId, taskInfoDayVO.getRequireType().toString())) {
						redisUtils.hset(TaskResource.REDIS_DAY_TASK_STATUS + userId, taskInfoDayVO.getRequireType().toString(), "0");
					}
					dayTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_DAY_TASK_STATUS + userId, taskInfoDayVO.getRequireType().toString()));
					redisUtils.expire(TaskResource.REDIS_DAY_TASK_STATUS + userId, DateHelper.getTodayLastTime());
					taskInfoDayVO.setGiftSort(TaskResource.Gift_DAY_Sort);
					taskInfoDayVO.setCurrentCount(dayTaskCount);
					// 查询每日礼包是否已经领取
					isDayGet = userTaskInfoMapper.selectIsGetReward(userId, TaskResource.GIFT_DAY_TYPE, taskInfoDayVO.getRequireType(), new Date());
					if(taskInfoDayVO.getRequireType().equals(TaskResource.GIFT_REQUIRE_INVIT_TYPE)){
						//查询邀请人当下所有被邀请人是否当天注册或绑定
						Integer inviteCount = null;
						inviteCount = inviteRelationMapper.selectAllInviteRelation(userId,new Date());
						dayTaskCount = inviteCount;
						redisUtils.hset(TaskResource.REDIS_DAY_TASK_STATUS + userId, taskInfoDayVO.getRequireType().toString(), inviteCount.toString());
					}
					if (isDayGet > 0) {
						taskInfoDayVO.setCurrentStatus(3);// 每天任务已领取
						taskInfoDayVO.setCurrentCount(taskInfoDayVO.getRequireCount());// 显示最大的任务数
						dayTaskCount = taskInfoDayVO.getRequireCount();
						taskInfoDayVO.setCurrentStatusName(TaskResource.CURRENT_ED_STATUS);
					} else if (dayTaskCount < taskInfoDayVO.getRequireCount()) {
						taskInfoDayVO.setCurrentStatus(2);// 每日任务进行中
						taskInfoDayVO.setCurrentStatusName(TaskResource.CURRENT_ING_STATUS);
					} else if (dayTaskCount >= taskInfoDayVO.getRequireCount()) {
						taskInfoDayVO.setCurrentStatus(1);// 每日任务可领取
						taskInfoDayVO.setCurrentCount(taskInfoDayVO.getRequireCount());// 显示最大的任务数
						dayTaskCount = taskInfoDayVO.getRequireCount();
						taskInfoDayVO.setCurrentStatusName(TaskResource.CURRENT_CAN_STATUS);
					}
					taskInfoDayVO.setTaskDesc(MessageFormat.format(taskInfoDayVO.getTaskDesc(), dayTaskCount.toString(), taskInfoDayVO.getRequireCount().toString()));
				}
			}
		}
		// 对每日任务进行排序
		if (dayTaskList.size() > 0 && dayTaskList != null) {
			Collections.sort(dayTaskList);
		}
		data.put("weekTaskList", weekTaskList);
		data.put("dayTaskList", dayTaskList);
		return data;
	}

	/**
	 * @Description： 领取奖励任务
	 * @author: WYZ
	 * @since: 2017年11月9日 下午6:13:21
	 */
	@Override
	public String reward(String userId, Integer giftType, Integer requireType) {
		String isSuccess = null;
		Integer userExtCount = 0;
		Integer userOtherCount = 0;
		Integer taskRewardCount = null;
		Integer isWeekDayGet = null;
		Integer weekTaskCount = null;
		Integer dayTaskCount = null;
		TaskInfo taskInfo = new TaskInfo();
		UserTaskInfo userTaskInfo = new UserTaskInfo();
		PointFlow pointFlow = new PointFlow();
		RedisUtils redisUtils = RedisUtils.getInstance();
		pointFlow.setOrderNo(UUIDUtils.getOrderNO());
		pointFlow.setArgs1(userId);
		pointFlow.setPaymentType(1);
		pointFlow.setCreateTime(new Date());

		userTaskInfo.setId(pointFlow.getOrderNo());
		userTaskInfo.setUserId(userId);
		userTaskInfo.setGiftType(giftType);
		userTaskInfo.setRequireType(requireType);
		userTaskInfo.setCreateTime(new Date());
		taskInfo = taskInfoMapper.selectReward(giftType, requireType);
		if (taskInfo == null) {
			return isSuccess = "202";// 202礼包类型错误
		}
		if(giftType == TaskResource.GIFT_SIGN_TYPE){
			// 查询每周的任务信息
			if (!redisUtils.hexists(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString())) {
				redisUtils.hset(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString(), "1");
			}
			weekTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_WEEK_TASK_STATUS + userId,TaskResource.GIFT_SIGN_TYPE.toString()));
			if (weekTaskCount == requireType){
				isWeekDayGet = userTaskInfoMapper.selectIsGetReward(userId, giftType, requireType, new Date());// 查询每周签到或者每日礼包是否已经领取
			}else{
				return isSuccess = "205";// 不符合礼包领取条件 
			}
		}else{
			if (!redisUtils.hexists(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString())) {
				redisUtils.hset(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString(), "0");
			}
			dayTaskCount = Integer.valueOf(redisUtils.hget(TaskResource.REDIS_DAY_TASK_STATUS + userId, requireType.toString()));
			if (dayTaskCount >= taskInfo.getRequireCount()) {
				isWeekDayGet = userTaskInfoMapper.selectIsGetReward(userId, giftType, requireType, new Date());// 查询每周签到或者每日礼包是否已经领取
			}else{
				return isSuccess = "205";// 不符合礼包领取条件 
			}
		}
		if (isWeekDayGet > 0) {
			return isSuccess = "203";// 203当日的礼包已领取
		}
		if (taskInfo != null) {
			//查询该用户是否有经验值的表
			UserOther userOther = new UserOther();
			userOther = userOtherMapper.selectByPrimaryKey(userId);
			if(userOther == null){
				UserOther userOtherN = new UserOther();
				userOtherN.setUserId(userId);
				userOtherN.setLevel(1);
				userOtherN.setExp(0);
				userOtherMapper.insert(userOtherN);
			}
			if (taskInfo.getPrizeCount2() == null) {
				taskInfo.setPrizeType2(0);
				taskInfo.setPrizeCount2(0);
			}
			if (taskInfo.getPrizeCount3() == null) {
				taskInfo.setPrizeType3(0);
				taskInfo.setPrizeCount3(0);
			}
			userTaskInfo.setGiftName(taskInfo.getGiftName());
			userTaskInfo.setPrizeType1(taskInfo.getPrizeType1());
			userTaskInfo.setPrizeType2(taskInfo.getPrizeType2());
			userTaskInfo.setPrizeType3(taskInfo.getPrizeType3());
			userTaskInfo.setPrizeCount1(taskInfo.getPrizeCount1());
			userTaskInfo.setPrizeCount2(taskInfo.getPrizeCount2());
			userTaskInfo.setPrizeCount3(taskInfo.getPrizeCount3());
			// 更新用户积分
			if (taskInfo.getPrizeType1().equals(TaskResource.PRIZE_GB_TYPE)) {
				userExtCount = userExtMapper.updateExt(userId, taskInfo.getPrizeCount1());
				pointFlow.setMoney(taskInfo.getPrizeCount1().toString());
			} else if (taskInfo.getPrizeType2().equals(TaskResource.PRIZE_GB_TYPE)) {
				userExtCount = userExtMapper.updateExt(userId, taskInfo.getPrizeCount2());
				pointFlow.setMoney(taskInfo.getPrizeCount2().toString());
			} else if (taskInfo.getPrizeType3().equals(TaskResource.PRIZE_GB_TYPE)) {
				userExtCount = userExtMapper.updateExt(userId, taskInfo.getPrizeCount3());
				pointFlow.setMoney(taskInfo.getPrizeCount3().toString());
			}
			// 更新用户经验
			if (taskInfo.getPrizeType1().equals(TaskResource.PRIZE_EXP_TYPE)) {
				userOtherCount = userOtherMapper.updateExp(userId, taskInfo.getPrizeCount1());
			} else if (taskInfo.getPrizeType2().equals(TaskResource.PRIZE_EXP_TYPE)) {
				userOtherCount = userOtherMapper.updateExp(userId, taskInfo.getPrizeCount2());
			} else if (taskInfo.getPrizeType3().equals(TaskResource.PRIZE_EXP_TYPE)) {
				userOtherCount = userOtherMapper.updateExp(userId, taskInfo.getPrizeCount3());
			}
			pointFlow.setOrderDetail(taskInfo.getGiftName());
			if (userExtCount > 0 || userOtherCount > 0) {
				taskRewardCount = userTaskInfoMapper.insertTaskReward(userTaskInfo);
				if (taskRewardCount > 0) {
					isSuccess = "200";
				}
			}
			if (userExtCount > 0) {
				pointFlowMapper.insertSelective(pointFlow);
			}

		}
		return isSuccess;
	}

}
